jRaiser.config({
	root : '/js/'
});

jRaiser.use([
	'node/1.0.x/node',
	'ajax/1.0.x/ajax',
	'template/1.0.x/template',
	'cookie/1.0.x/cookie'
], function($, ajax, template, cookie) {

/**
 * 登录视图
 */
var loginView = $('#login-view');
loginView._renderForm = function() {
	this.css('top', parseInt(
		( document.documentElement.clientHeight - this.size('padding border').height ) / 2.5
	) + 'px').css('visibility', 'visible');
	
	$('form', this).on('submit', function(e) {
		e.preventDefault();
		
		var nickname = $('input[type=text]', this).val().trim();
		if (nickname) {
			ajax.send({
				url : this.action,
				method : 'POST',
				dataType : 'json',
				data : { nickname : nickname },
				onsuccess : function(ret) {
					if (typeof ret === 'string') {
						alert(ret);
					} else {
						cookie.set('name', ret.name);
						cookie.set('password', ret.password);
						viewManager.render('room-view');
					}
				}
			});
		} else {
			alert('请输入昵称');
		}
	});
};
loginView.render = function() {
	var self = this;
	
	if ( cookie.get('name') && cookie.get('password') ) {
		ajax.send({
			url : '/player/get',
			dataType : 'json',
			nocache : true,
			onsuccess : function(ret) {
				if (ret) {
					viewManager.render('room-view');
				} else {
					self._renderForm();
				}
			}
		});
	} else {
		self._renderForm();
	}
};
loginView.dispose = function() {
	$('form', this).off('submit');
	this.css('visibility', '');
};


// 包装一些公共操作
function _wrapRes(fn) {
	return function(ret) {
		if (ret != null && ret.type === 'error') {
			alert(ret.message);
			if (ret.status === 0) {
				viewManager.render('login-view');
			}
		} else {
			fn.call(this, ret);
		}
	};
}


/**
 * 房间视图
 */
var roomView = $('#room-view');
roomView._template = '<ol>\
<#\
for (var i = 0, j, players; i < data.length; i++) {\
	if (!data[i]) { continue; }\
	players = data[i].players;\
#>\
<li<# if (players == null || players.length < 4) { #> class="room-notfull"<# } #> data-roomid="<#=i#>">\
	<h2>房间<#=i #> &raquo;</h2>\
<# if (players != null && players.length) { #>\
	<ol class="players">\
	<# for (j = 0; j < players.length; j++) { #>\
		<li><#=players[j].name #></li>\
	<# } #>\
	</ol>\
<# } #>\
</li>\
<# } #>';
roomView._renderRoomList = function(data) {
	if (data.length) {
		$('.rooms', this).html(
			template.parse(this._template, { data : data })
		).find('.room-notfull').on('click', function() {
			ajax.send({
				url : '/room/enter',
				method : 'POST',
				dataType : 'json',
				data : {
					roomId : this.getAttribute('data-roomid')
				},
				onsuccess : _wrapRes(function(ret) {
					viewManager.render('game-view', ret);
				})
			});
		});
	}
	
	this._loadData();
};
roomView._loadData = function() {
	var self = this;
	
	if (self._xhr) {
		self._xhr.abort();
	}
	
	self._xhr = ajax.send({
		url : '/room/list' + (self._timestamp ? '/' + self._timestamp : ''),
		nocache : true,
		dataType : 'json',
		onsuccess : _wrapRes(function(ret) {
			delete self._xhr;
			if (ret) {
				self._timestamp = ret.timestamp;
				self._renderRoomList(ret.list);
			}
		})
	});
};
roomView.render = function() {
	$('#create-room').click(function() {
		ajax.send({
			url : '/room/create',
			method : 'POST',
			dataType : 'json',
			onsuccess : _wrapRes(function(ret) {
				viewManager.render('game-view', ret);
			})
		});
	});
	
	this._loadData();
	
	this.css('visibility', 'visible');
};
roomView.dispose = function() {
	if (this._xhr) {
		this._xhr.abort();
		delete this._xhr;
	}
	
	this.css('visibility', '').find('div.rooms').html('');
	
	$('#create-room').off('click');
};


/**
 * 游戏视图
 */
var gameView = $('#game-view');
gameView._template = '<div class="center-area">\
<#\
	if (data.lastPokers != null) { #>\
<ul class="pokers pokers-horizontal">\
	<#\
		for (var i = 0; i < data.lastPokers.pokers.length; i++) { #>\
			<li class="poker-<#=(data.lastPokers.pokers[i].toString().replace(".", "-")) #>"></li>\
	<#\
		} #>\
</ul>\
<#\
	} #>\
</div><#\
	var directions = ["bottom", "right", "top", "left" ];\
	for (var i = 0, player; i < data.players.length; i++) {\
		player = data.players[i]; #>\
<div class="player-<#=directions[i] #><# if (player.name === data.myName) { #> player-me<# } #>">\
	<div class="player-info">\
		<strong class="player-name"><#=player.name #></strong><# if (data.masterName !== player.name && player.isReady) { #>(Ready)<# } #>：<em class="score"><#=(player.score ? "-" + player.score : 0) #></em>\
<#\
		if (player.name === data.myName) {\
			if (data.started) {\
				if (data.nextActorName === data.myName) { #>\
		<input type="button" value="出牌" class="btn-submitpokers" />\
		<input type="button" value="PASS" class="btn-pass" />\
<#\
				}\
			} else {\
				if (data.masterName === data.myName) { #>\
		<input type="button" value="开始" class="btn-startgame" />\
<#\
				} else if (player.isReady) { #>\
		<input type="button" value="取消" class="btn-cancelready" />\
<#\
				} else if (!player.isReady) { #>\
		<input type="button" value="准备" class="btn-setready" />\
<#\
				}\
			}\
		}\
		if (!player.isReady && player.name === data.myName) { #>\
		<input type="button" value="离开" class="btn-exit" />\
<#\
		}\
#>\
	</div>\
<#\
		if (player.pokers != null) { #>\
	<ul class="pokers pokers-<#=(i % 2 ? "vertical" : "horizontal") #>">\
<#\
			if (typeof player.pokers === "number") {\
				for (var j = 0; j < player.pokers; j++) { #>\
		<li class="poker"></li>\
<#\
				}\
			} else { \
				for (var j = 0; j < player.pokers.length; j++) { #>\
		<li class="poker-<#=(player.pokers[j].toString().replace(".", "-")) #>" data-poker="<#=player.pokers[j]#>"></li>\
<#\
				}\
			} #>\
	</ul>\
<#\
		} #>\
</div>\
<#\
	} #>';
gameView._loadData = function(id) {
	var self = this;
	
	this._socket = ajax.send({
		url : 'room/query/' + id + '/' + self._timestamp,
		nocache : true,
		dataType : 'json',
		onsuccess : _wrapRes(function(ret) {
			self.render(ret);
		})
	});
};
gameView.render = function(data) {
	var self = this;

	switch (typeof data) {
		case 'object':
			this._roomId = data.id;
			
			var players = data.players, playerName = cookie.get('name'), pos = -1, i;
			for (i = players.length - 1; i >= 0; i--) {
				if (players[i].name === playerName) {
					pos = i;
					break;
				}
			}
			// 重新排列玩家，自己永远在最前（下方）
			if (pos !== 0) {
				var sortedPlayers = [ ];
				for (i = pos; i < players.length; i++) {
					sortedPlayers.push(players[i]);
				}
				for (i = 0; i < pos; i++) {
					sortedPlayers.push(players[i]);
				}
				data.players = sortedPlayers;
			}
			
			data.myName = playerName;
			
			this.html(
				template.parse(this._template, { data : data })
			).css('visibility', 'visible');
			
			var centerArea = this.find('.center-area');
			centerArea.css('margin-top',
				(document.documentElement.clientHeight - centerArea.size('padding border').height) / 2
			);
			
			$('.btn-exit', this).click(function() {
				ajax.send({
					method : 'POST',
					url : 'room/exit',
					dataType : 'json',
					onsuccess : _wrapRes(function() {
						viewManager.render('room-view');
					})
				});
			});
			
			$('.btn-setready', this).click(function() {
				ajax.send({
					method : 'POST',
					url : 'room/setready',
					dataType : 'json',
					onsuccess : _wrapRes(function() {
						
					})
				});
			});
			
			$('.btn-cancelready', this).click(function() {
				ajax.send({
					method : 'POST',
					url : 'room/cancelready',
					dataType : 'json',
					onsuccess : _wrapRes(function() {
						
					})
				});
			});
			
			$('.btn-startgame', this).click(function() {
				ajax.send({
					method : 'POST',
					url : 'room/startgame',
					dataType : 'json',
					onsuccess : _wrapRes(function() {
						
					})
				});
			});
			
			$('.player-me .pokers li', this).click(function(e) {
				$(this).toggleClass('poker-selected');
			});
			
			$('.btn-submitpokers, .btn-pass', this).click(function(e) {
				var value = [ ];
				// TODO 右键出牌
				if (this.className.indexOf('pass') === -1) {
					$('.poker-selected', self).each(function(elt) {
						value.push( elt.getAttribute('data-poker') );
					});
					
					if (!value.length) {
						alert('请选择要出的牌');
						return;
					}
				}
				
				ajax.send({
					method : 'POST',
					url : 'room/submitpokers',
					dataType : 'json',
					data : {
						value : value.join(',')
					},
					onsuccess : _wrapRes(function(ret) {
						
					})
				});
			});
			
			self._timestamp = data.timestamp;
			break;
			
		case 'number':
			this._roomId = data;
			break;
	}
	
	this._loadData(this._roomId);
};
gameView.dispose = function() {
	this.html('').css('visibility', 'hidden');
	
	if (this._socket) {
		this._socket.abort();
		delete this._socket;
	}
};


/**
 * 视图管理器
 */
var viewManager = {
	views : {
		'login-view' : loginView,
		'room-view' : roomView,
		'game-view' : gameView
	},
	
	render : function(id) {
		if (this._currentView) {
			this._currentView.dispose();
		}
		
		var args = Array.prototype.slice.call(arguments, 1), view = this.views[id];
		
		view.render.apply(view, args);
		this._currentView = view;
	}
};

viewManager.render('login-view');

});